# Create your views here.

from django.shortcuts import render
from django.http import HttpResponseRedirect
from contact.models import ContactForm
from contact.models import Message
from django.utils import timezone

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            a =form.cleaned_data['author']
            c = form.cleaned_data['content']
            p = timezone.now()
            newMessage = Message(author=a,content=c,pubDate=p)
            newMessage.save()
            return HttpResponseRedirect('/contact/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form
    
    latestMessages = Message.objects.all().order_by('-pubDate')[:10]
    return render(request, 'contact/contact.html', {
        'latestMessages': latestMessages,
        'form': form,
    })